package cn.mrlong.basicframework.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.http.SslError;
import android.os.Build;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Created by ly343 on 2018/12/28.
 */

public class WebViewUtils {

    private WebView webview;
    private String goToUrl;
    private StatuListener listener;
    private boolean isStar = false;

    public WebViewUtils(WebView webview) {
        this.webview = webview;
    }

    public void setUrl(String url) {
        goToUrl = url;
    }

    public void setStatuListener(StatuListener statulistener) {
        listener = statulistener;
    }

    public interface StatuListener {
        void onProgressChanged(int i);

        void error(WebResourceError e);

        void onPageFinished();
    }

    public WebViewUtils(WebView webview, String goToUrl) {
        this.webview = webview;
        this.goToUrl = goToUrl;
    }

    public void callJS(String methodName, String paramsJson) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webview.evaluateJavascript("javascript:" + methodName + "(" + paramsJson + ")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        } else {
            webview.loadUrl("javascript:" + methodName + "(" + paramsJson + ")");
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void startWevView() {
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setBuiltInZoomControls(true);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setUseWideViewPort(true);
        webview.getSettings().setSavePassword(false);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (null != listener)
                    listener.onPageFinished();
            }

            //处理网页加载失败时
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                if (null != listener)
                    listener.error(error);

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (null != listener) {
                    listener.onProgressChanged(newProgress);
                    Log.e("=============>", newProgress + "");
                }
            }

            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                Log.d("WebView===>", message + " -- From line "
                        + lineNumber + " of "
                        + sourceID);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d("WebView===>", "[" + consoleMessage.messageLevel() + "] " + consoleMessage.message() + "(" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + ")");
                return super.onConsoleMessage(consoleMessage);
            }


        });
        webview.loadUrl(goToUrl);
        isStar = true;
    }

    //返回
    public void goBack(Activity activity) {
        if (webview.canGoBack()) {
            webview.goBack();
        } else {
            activity.finish();
        }
    }

    //销毁
    public void webViewRelease() {
        if (webview != null) {
            webview.clearCache(true);
            webview.clearFormData();
            webview.clearMatches();
            webview.clearSslPreferences();
            webview.clearDisappearingChildren();
            webview.clearHistory();
            webview.clearAnimation();
            webview.loadUrl("about:blank");
            webview.removeAllViews();
            webview.freeMemory();
            isStar = false;
        }
    }

    public void webViewOnResume() {
        webview.onResume();
    }

    public void webViewOnPause() {
        webview.onPause();
    }
}
